﻿using System;
using CommandRunner.Contract;
using CommandRunner.Core;
using CommandRunner.Model;
using CommandRunner.WCFDataTransport;
using CommandSavvy;

namespace CommandRunner.Console.Command
{
    public class SingleCommand : SavvyCommand
    {
        private SingleCommandOptions SingleCommandOptions { get { return (SingleCommandOptions)Options; } }

        public override string Key
        {
            get { return "singlecommand"; }
        }

        public override string Description
        {
            get { return "Run a single command"; }
        }

        public override int Execute()
        {
            Runner runner = SetupSingleCommandRunner(SingleCommandOptions.Command, SingleCommandOptions.Server, SingleCommandOptions.Port, SingleCommandOptions.WorkDir, SingleCommandOptions.Interactive, SingleCommandOptions.Monitor);
            runner.CommandCompleted += CommandRunnerConsoleOutput.CommandOutput;
            runner.CommandSkipped += CommandRunnerConsoleOutput.SkippedOutput;
            runner.CommandFailed += CommandRunnerConsoleOutput.ErrorOutput;

            CommandExecutionStatus success = runner.RunCommands();

            if (success == CommandExecutionStatus.Success)
                return (int)SavvyCommandReturnCode.SUCCESS;
            else
                return (int)SavvyCommandReturnCode.FAILURE;

        }

        private static Runner SetupSingleCommandRunner(string command, string server, Nullable<int> port, string workingDirectory, bool interactive, bool monitorSuccess)
        {
            ICommandRunnerConfigurationManager configManager = new ConfigurationManagerSingleCommand(command, server, port, workingDirectory, interactive, monitorSuccess);
            ICommandRunnerClientDataTransport dataTransport = new CommandRunnerClient();
            Runner commandRunner = new Runner(configManager, dataTransport);
            return commandRunner;
        }
    }
}
